package com.odt.outdoor.net;



import com.google.gson.JsonSyntaxException;
import com.shaomengjie.okhttp.AbstractCallback;
import com.shaomengjie.okhttp.AppException;
import com.shaomengjie.okhttp.JsonParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by shaomengjie on 2017/3/14.
 */

public abstract class Callback<T> extends AbstractCallback<T> {

    @Override
    public T convert(String content) throws AppException {
        try {
            Type genericSuperclass = getClass().getGenericSuperclass();
            genericSuperclass = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
            JSONObject jsonObject = new JSONObject(content);
            int code = jsonObject.getInt("code");
            if (code == ResponseCode.CODE_SUCCESS){
                String data = jsonObject.opt("data").toString();
                return JsonParser.deserializeFromJson(data,genericSuperclass);
            }else {
                throw new AppException(code,jsonObject.getString("msg"));
            }
        } catch (JsonSyntaxException e) {
            throw new AppException(AppException.ErrorType.JSON, e.getMessage());
        } catch (JSONException e) {
            throw new AppException(AppException.ErrorType.JSON, e.getMessage());
        } catch (Exception e){
            throw new AppException(AppException.ErrorType.JSON, e.getMessage());
        }
    }
}
